<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Controller;

use App\Call\PassportCall;
use App\Call\ResourceCall;
use App\Middleware\JwtParse;
use App\Model\ShoppingCart;
use App\Utils\SnowflakeUtils;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\PostMapping;
use App\Middleware\SelfJwtAuth;


/**
 * @Controller(prefix="/ecommerce/php/shoppingcart")
 * Class IndexController
 * @package App\Controller
 */
class ShoppingCartController extends BaseAbstractController
{
    /**
     * @PostMapping(path="create")
     * @Middleware(SelfJwtAuth::class)
     *
     * @return array
     */
    public function create()
    {
        $jsonArr = json_decode($this->request->post('dataJson'), true);
        if (!is_array($jsonArr)) {
            return self::returnFailed('数据错误', 22);
        }

        $validator = $this->validationFactory->make(
            $jsonArr,
            [
                'SkuId' => 'required|integer',
                'Count' => 'integer',
                'AppId' => 'integer',
                'SaleStrategyId' => 'integer',
                'IsSilentlyJoin' => 'integer|required',
                'PurchaserType' => 'integer',
                'PurchaserName' => 'alpha_num'
            ],
        );

        if ($validator->fails()) {
            return self::returnFailed($validator->errors()->first(), 22);
        }

        $isSilentlyJoin = $jsonArr['IsSilentlyJoin'];

        //查询内容管理系统，获取ContentId
        [$ok, $data] = ResourceCall::getResourceInfoBySkuId((int)$jsonArr['SkuId']);
        if ($ok) {
            return self::returnFailed($ok, 22);
        }

        $content = $data['Content'] ?? [];

        //获取资源Id
        $contentId = $content['Id'] ?? 0;
        if (!$contentId) {
            return self::returnFailed('没有获取到资源id', 22);
        }

        //判断库存
        if ($data['IsVirtualProduct'] < 1 && $data['Quantity'] < $jsonArr['Count']) {
            return self::returnFailed('库存不足', 22);
        }

        //获取店铺信息
        [$ok, $orgObject] = PassportCall::getContentsFromOrg([$contentId], $this->request->post());
        if ($ok) {
            return self::returnFailed($ok, 22);
        }

        $shopInfo = current($orgObject);

//        $isVirtualProduct = $content['IsVirtualProduct'] ?? 0;

        //检查是否加入过购物车
//        $shoppingCart = ShoppingCart::query()->where([
//            ['ObjectId', '=', $contentId],
//            ['SkuId', '=', $jsonArr['SkuId']],
//            ['PurchaserId', '=', $this->tmpUserId],
//            ['IsSilentlyJoin', '=', $jsonArr['IsSilentlyJoin'],
//            ]
//        ])->first();
//        if ($shoppingCart) {
//            return self::returnFailed('重复加入购物车', 22);
//        }

        $gId = SnowflakeUtils::getIds();

        $userInfo = $this->request->getAttribute(JwtParse::CUSTOM_ATTR_KEY);

        $content = $data['Content'];
        $shoppingCart = new ShoppingCart();
        $shoppingCart->Id = $gId['Id'];
        $shoppingCart->ExternalId = $gId['ExternalId'];
        $shoppingCart->Count = $jsonArr['Count'] ?? 1;
        $shoppingCart->AppId = $jsonArr['AppId'] ?? 0;
        $shoppingCart->IsSilentlyJoin = $isSilentlyJoin;
        $shoppingCart->ObjectId = $contentId;
        $shoppingCart->ObjectTypeId = $content['ObjectTypeId'] ?? 0;
        $shoppingCart->ObjectTypeTitle = $content['ObjectTypeTitle'] ?? 0;
        $shoppingCart->Price = $data['CurrentPrice'] ?? 0.00;
        $shoppingCart->PurchaserId = $userInfo['UserId'];
        $shoppingCart->PurchaserName = 'user' . $this->tmpUserId;
        $shoppingCart->PurchaserType = 1;
        $shoppingCart->SkuId = $jsonArr['SkuId'];
        $shoppingCart->TotalMoney = $shoppingCart->Count * $shoppingCart->Price;
        $shoppingCart->ShopId = $shopInfo['OrganizationId'];
        if (true === $shoppingCart->save()) {
            return self::returnSuccess();
        }

        return self::returnFailed('写入失败', 22);
    }

    /**
     * @GetMapping(path="list")
     * @return  array
     */
    public function list()
    {
        $postData = $this->request->query();
        $validator = $this->validationFactory->make($postData, [
            'cp' => 'required|integer',
            'ps' => 'required|integer',
            'sortType' => 'alpha_num',
            'sortFieldName' => 'alpha_num'
        ]);

        if ($validator->fails()) {
            return self::returnFailed($validator->errors()->first());
        }

        $data = $validator->validated();
        $modelQuery = ShoppingCart::where('IsDeleted', 0);
        $count = $modelQuery->count();

        if (isset($data['sortType']) && isset($data['sortFieldName'])) {
            $modelQuery->orderBy($data['sortFieldName'], $data['sortType']);
        }

        $res = $modelQuery->forPage($data['cp'], $data['ps'])->get();

        return self::returnSuccess([
            'Count' => $count,
            'Items' => $res
        ]);
    }

    /**
     * @PostMapping(path="delete")
     * @Middleware(SelfJwtAuth::class)
     * @return array
     */
    public function delete()
    {
        $id = $this->request->post('ids');
        $idArr = explode(',', $id);
        if ($idArr) {
            ShoppingCart::destroy($idArr);
        } else {
            return self::returnFailed('ids不能为空');
        }

        return self::returnSuccess();
    }

    /**
     * @GetMapping(path="detail")
     * @Middleware(SelfJwtAuth::class)
     * @return array
     */
    public function detail()
    {
        $id = $this->request->query('id');
        if(!is_numeric($id)) {
            return self::returnFailed('id错误');
        }

        $res = ShoppingCart::where([
            'Id' => $id,
            'PurchaserId' => ($this->request->getAttribute(JwtParse::CUSTOM_ATTR_KEY))['UserId']
        ])->limit(1)->first();

        return self::returnSuccess($res);
    }

    /**
     * @PostMapping(path="update")
     * @return array
     */
    public function update()
    {
        $id = $this->request->post('id');
        if(!is_numeric($id)) {
            return self::returnFailed('id错误');
        }

        $model = ShoppingCart::find($id);
        if(!$model) {
            return self::returnFailed('没有找到要更新的数据');
        }

        return self::returnSuccess();
    }
}
